{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e7481b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from ollama import Client\n",
    "from dotenv import load_dotenv\n",
    "import gradio as gr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64c8bc7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "load_dotenv(override=True)\n",
    "\n",
    "OLLAMA_BASE_URL=\"https://www.ollama.com\"\n",
    "API_KEY=os.environ.get(\"OLLAMA_API_KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7445168",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_prompt= \"\"\"\n",
    "    You are a helpful assistant who responds to the user queries.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6f88855",
   "metadata": {},
   "outputs": [],
   "source": [
    "ollama = Client(\n",
    "    host=OLLAMA_BASE_URL,\n",
    "    headers={'Authorization': 'Bearer ' + os.environ.get('OLLAMA_API_KEY')}\n",
    ")\n",
    "\n",
    "def stream_chat(prompt):\n",
    "    messages = [\n",
    "        {\"role\":\"system\", \"content\": system_prompt},\n",
    "        {\"role\":\"user\", \"content\": prompt}\n",
    "        ]\n",
    "    result = ollama.chat(\n",
    "        model=\"gpt-oss:120b\",\n",
    "        messages=messages, \n",
    "        stream=True)\n",
    "\n",
    "    response = \"\"\n",
    "    for chunk in result:\n",
    "        response += chunk['message']['content']\n",
    "        yield response\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a4f28a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "message_input = gr.Textbox(label=\"Input\")\n",
    "message_output = gr.Markdown(label=\"Answer\")\n",
    "\n",
    "view = gr.Interface(\n",
    "    fn=stream_chat,\n",
    "    title=\"Welcome to Ollama Cloud\", \n",
    "    inputs=[message_input], \n",
    "    outputs=[message_output], \n",
    "    examples=[\n",
    "        \"Explain the Transformer architecture to a layperson\",\n",
    "        \"Explain the Transformer architecture to an aspiring AI engineer\",\n",
    "        ], \n",
    "    flagging_mode=\"never\"\n",
    "    )\n",
    "\n",
    "view.launch(inbrowser=True)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
